package org.mao.parser;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.mao.forum.dao.ForumPostDao;
import org.mao.forum.dao.ForumSectionDao;
import org.mao.forum.entity.ForumPost;
import org.mao.forum.entity.ForumSection;
import org.mao.forum.vo.ForumTaskParamsVo;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Lists;

public abstract class BaseForumParser {

	private static Logger logger = Logger.getLogger(BaseForumParser.class);

	@Autowired
	private ForumSectionDao forumSectionDao;

	@Autowired
	private ForumPostDao forumPostDao;

	// 根据一个板块，列出要读的每页的url
	protected List<String> readSectionList(Integer sectionId, ForumTaskParamsVo paramsVo) {
		List<String> sectionList = Lists.newArrayList();
		try {
			ForumSection forumSection = new ForumSection();
			forumSection.setId(sectionId);
			forumSection = forumSectionDao.get(forumSection);
			String url = forumSection.getUrl();
			if (StringUtils.isNotBlank(url)) {
				if (url.endsWith("1.html")) {
					url = url.replace("1.html", "");
				}
				paramsVo = this.parseParams(paramsVo);
				Integer fromPage = paramsVo.getFromPage();
				Integer toPage = paramsVo.getToPage();
				for (int i = fromPage; i <= toPage; i++) {
					String sectionUrl = url + i + ".html";
					logger.info("read section url:" + sectionUrl);
					sectionList.add(sectionUrl);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return sectionList;
	}

	// 初始化ForumPost
	protected ForumPost initForumPost(String postNumber, String postName, Integer sectionId, String url) {
		ForumPost forumPost = new ForumPost();
		forumPost.setPostNumber(postNumber);
		forumPost = forumPostDao.get(forumPost);
		if (forumPost == null) {
			forumPost = new ForumPost();
			forumPost.setPostNumber(postNumber);
			forumPost.setName(postName);
			forumPost.setSectionId(sectionId);
			forumPost.setUrl(url);
		}
		return forumPost;
	}

	private ForumTaskParamsVo parseParams(ForumTaskParamsVo paramsVo) {
		if (paramsVo == null) {
			paramsVo = new ForumTaskParamsVo();
			paramsVo.setFromPage(1);
			paramsVo.setToPage(1);
		} else {
			if (paramsVo.getFromPage() == null) {
				paramsVo.setFromPage(1);
			}
			if (paramsVo.getToPage() == null) {
				paramsVo.setToPage(paramsVo.getFromPage());
			}
		}
		return paramsVo;
	}

}
